package com.itheima.service.impl;

import com.itheima.mapper.MemberMapper;
import com.itheima.pojo.Member;
import com.itheima.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

@Service
@Slf4j
public class MemberServiceImpl implements MemberService {
    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    /**
     * 登录
     * @param telephone
     * @param validateCode
     * @return
     */
    public Boolean login(String telephone, String validateCode){
        String code = redisTemplate.opsForValue().get("validateCode:" + telephone);
        log.info("验证码:{} : {}", code, validateCode);
        // 验证码校验
        if(code == null || !code.equals(validateCode)){
            log.info("验证码错误");
            return false;
        }else {
            log.info("验证码正确");
            Member member = memberMapper.selectByIdPhone(telephone);
            log.info("member:{}", member);
            if(member == null){
                log.info("会员不存在，数据库需要保存该信息");
                member = new Member();
                member.setIdCard("unknown");
                member.setFileNumber("unknown");
                member.setName("unknown");
                member.setSex("unknown");
                member.setPhoneNumber(telephone);
                member.setRegTime(LocalDate.now());
                member.setPassword("123456");
                log.info("member:{}", member);
                if(memberMapper.insert(member) < 1){
                    throw new RuntimeException("新增会员失败");
                }
            }
            return true;
        }

    }
}
